package com.seabook.store.auth.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class AuthFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest requestHttp = (HttpServletRequest) request;
        String requestURI = requestHttp.getRequestURI().toLowerCase();
        requestURI = requestURI.replaceAll("webstore/", "");
        boolean needLogin = requestURI.indexOf("order/") != -1
                || requestURI.indexOf("account/") != -1
                || requestURI.indexOf("admin/") != -1;
        if (needLogin
                && UserSession.getUserSession((HttpServletRequest) request)
                        .getUser() == null) {
            request.setAttribute("message", "");
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/login.do");
            request.setAttribute("forwardAction", requestURI);
            requestDispatcher.forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }
}
